package com.jl.process.util;

import java.io.PrintStream;

import org.eclipse.ui.console.IOConsole;
import org.mozilla.javascript.JavaScriptException;
import org.mozilla.javascript.RhinoException;
import org.mozilla.javascript.ScriptStackElement;

import com.jl.js.console.ConsoleShell;

public class ExceptionTools {
	public static final String ERROR_TAG = "Exception Detail:";


	private ExceptionTools() {
	}

	/**
	 * print the RhinoException
	 * @param consoleShell 
	 * 
	 * @param e
	 * @param s
	 */
	public static void printRhinoExceptionMessage(ConsoleShell consoleShell, Exception e, PrintStream s) {
		if (e instanceof JavaScriptException) {
			JavaScriptException jse = (JavaScriptException) e;
			s.println(jse.getMessage());
			s.println(jse.getScriptStackTrace());
			return;
		} else if (e instanceof RhinoException) {
			RhinoException re = (RhinoException) e;
			printStackTraceAndMakeHyperlink(consoleShell.getConsole(),re,s);
			return;
		} else {
			s.println(e.getMessage());
		}
		StackTraceElement[] st = e.getStackTrace();
		for (int i = 0; i < st.length; i++) {
			String filename = st[i].getFileName();
			if ((filename != null)
					&& (filename.endsWith(".js") || filename.endsWith(".xml"))) {
				int linenumber = st[i].getLineNumber();
				if (linenumber >= 1) {
					s.println("\tat " + filename + ":" + linenumber);
				}
			}
		}
	}
	
	
	private static void printStackTraceAndMakeHyperlink(IOConsole console, RhinoException re, PrintStream s) {
		String message = re.getMessage();
		s.print(ERROR_TAG);
		s.print("\n");
		s.print(message.substring(0 , message.lastIndexOf('(')));
		s.print("\n");
		ScriptStackElement[]  eles = re.getScriptStack();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < eles.length; i++) {
			eles[i].renderJavaStyle(sb);
			sb.append("\n");
		}
		s.print(sb.toString());
	}

}
